package com.lanou.bookstore.cart.web.servlet;

import com.lanou.bookstore.book.domain.Book;
import com.lanou.bookstore.book.service.BookService;
import com.lanou.bookstore.cart.domain.Cart;
import com.lanou.bookstore.cart.domain.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    private BookService bookService = new BookService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bid = request.getParameter("bid");
        Integer count = Integer.parseInt(request.getParameter("count"));
        Book book = bookService.findByBid(bid);
        CartItem cartItem = new CartItem(book, count);
        Cart carts = (Cart) request.getSession().getAttribute("carts");

        carts.getCartItems().put(book.getBname(), cartItem);
        request.getRequestDispatcher("/jsps/cart/list.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bid = request.getParameter("bid");
        if (bid == null) {
            Cart carts = (Cart) request.getSession().getAttribute("carts");
            Map<String, CartItem> cartItems = carts.getCartItems();
            Set<String> keySet = cartItems.keySet();
            List<String> stringList = new ArrayList<>();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String s = iterator.next();
                if (s != null) {
                    stringList.add(s);
                }
            }
            for (String s : stringList) {
                cartItems.remove(s);
            }
            response.sendRedirect("/jsps/cart/list.jsp");
        } else if (bid != null) {
            Cart carts = (Cart) request.getSession().getAttribute("carts");
            Map<String, CartItem> cartItems = carts.getCartItems();
            Book book = bookService.findByBid(bid);
            cartItems.remove(book.getBname());
            response.sendRedirect("/jsps/cart/list.jsp");
        }

    }
}
